package com.it.security.rbac;


import com.it.security.JWTUser;
import com.it.security.sys.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @program: learning
 * @description: 自定义授权
 * @author: Lefnmg
 * @create: 2018-11-20 21:02
 **/
@Component
public class RbacService {
    @Autowired
    private UserService userService;
//    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public boolean hasPermission(HttpServletRequest request, Authentication auth) {
        boolean hasPermission =false;
        Object principal = auth.getPrincipal();

        // 只有对非匿名用户才有必要进行权限控制
        if (principal instanceof JWTUser) {
            String username = ((JWTUser) principal).getUsername();

            // 根据username 查询用户所拥有权限的所有URL
            List<String> urls = userService.findPermissionsByUsername(username);
            // 遍历判断用户所访问的请求是否在其权限允许的范围内
            System.out.println(request.getRequestURI());
            String requestURI = request.getRequestURI();
            for (String url:urls) {
                if (requestURI.startsWith(url)){
                    hasPermission =true;
                    break;
                }
            }
        }

        return hasPermission;
    }

}
